<template>
    <a-layout>
      <a-breadcrumb style="background-color: white; margin-left: 5px">
        <a-breadcrumb-item>
          <router-link to="/">首页</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <router-link to="/admin/course">课程管理</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>直播管理</a-breadcrumb-item>
      </a-breadcrumb>
      <a-layout-content
        :style="{
          background: '#fff',
          padding: '24px',
          margin: 0,
          minHeight: '280px',
        }"
      >
        <a-space size="small">
          <a-button type="primary" @click="createLiveContent">
            新增课时
          </a-button>
          <a-button type="default" @click="handleQuery"> 刷新 </a-button>
          <br />
          <br />
        </a-space>
        <a-table
          :columns="columns"
          :row-key="(record) => record.id"
          :data-source="liveContents"
          :pagination="pagination"
          :loading="loading"
          bordered
        >
          <!-- moment(paper.value.startDate).format("YYYY-MM-DD") -->
          <template #status="{ record }">
            <a-tag
              color="green"
              :visible="
                new Date(record.beginTime).getTime() > new Date().getTime()
              "
              >未开始</a-tag
            >
            <a-tag
              color="blue"
              :visible="
                new Date(record.beginTime).getTime() <= new Date().getTime() &&
                !record.liveTime
              "
              >正在上课
            </a-tag>
            <a-tag
              color="yellow"
              :visible="
                new Date(record.beginTime).getTime() <= new Date().getTime() &&
                !!record.liveTime
              "
              >已结束
            </a-tag>
          </template>
          <template #backVideo="{ record }">
            <a-tag color="green" :visible="!record.backVideo">未生成</a-tag>
            <a-tag color="blue" :visible="!!record.backVideo">已生成</a-tag>
          </template>
          <template v-slot:action="{ text, record }">
            <a-space size="small">
              <a-button type="primary" @click="edit(record)"> 编辑 </a-button>
              <a-button type="primary" @click="handleDelete(record)" danger>
                删除
              </a-button>
              <a-button
                type="primary"
                @click="startLive(record)"
                style="background-color: #0aa679"
              >
                去直播
              </a-button>
            </a-space>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
    <a-modal
      title="直播课时表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="clearValidate"
    >
      <a-form
        ref="liveContentRef"
        :rules="rules"
        :model="liveContent"
        :label-col="{ span: 6 }"
      >
        <a-form-item label="标题" name="name">
          <a-input v-model:value="liveContent.name" />
        </a-form-item>
        <a-form-item label="章节序号" name="sort">
          <a-input v-model:value="liveContent.sort" type="number" />
        </a-form-item>
        <a-form-item label="回放地址" name="backVideo">
          <a-input v-model:value="liveContent.backVideo" />
        </a-form-item>
        <a-form-item label="开课日期" name="beginDate">
          <a-date-picker v-model:value="liveContent.beginDate" />
        </a-form-item>
        <a-form-item label="开课时间" name="beginTime">
          <a-time-picker v-model:value="liveContent.beginTime" format="HH:mm" />
        </a-form-item>
      </a-form>
    </a-modal>
  </template>
  
  <script lang="ts">
  import { createVNode, defineComponent, onMounted, ref } from "vue";
  import axios from "axios";
  import { message, Modal } from "ant-design-vue";
  import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
  import { Tool } from "@/util/tool";
  import { useRoute, useRouter } from "vue-router";
  import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
  import moment from "moment";
  import "moment/locale/zh-cn";
  
  moment.locale("zh-cn");
  
  export default defineComponent({
    name: "AdminLiveContent",
    components: {
      PlusOutlined,
    },
    setup() {
      const liveContents = ref();
      const router = useRouter();
      // 路由对象 用于获取queryId
      const route = useRoute();
      // 表示加载状态
      const loading = ref(false);
      // 页码信息
      const pagination = ref({
        current: 1,
        pageSize: 10,
        total: 0,
      });
      // 表格列信息
      const columns = [
        {
          title: "序号",
          dataIndex: "sort",
        },
        {
          title: "标题",
          dataIndex: "name",
        },
        {
          title: "直播时长(s)",
          dataIndex: "liveTime",
        },
        {
          title: "回放状态",
          key: "backVideo",
          slots: { customRender: "backVideo" },
        },
        {
          title: "开课日期",
          dataIndex: "beginDate",
        },
        {
          title: "状态",
          key: "beginTime",
          slots: { customRender: "status" },
        },
        {
          title: "操作",
          key: "action",
          slots: { customRender: "action" },
        },
      ];
  
      /**
       * 数据查询
       */
      const handleQuery = async (params: any) => {
        await axios
          .get("/api/admin/live/content/list", {
            params: {
              liveId: route.query.courseId,
              // page: params.page,
              // size: params.size
            },
          })
          .then((response) => {
            const data = response.data;
            if (data.success) {
              liveContents.value = data.content.list;
            } else {
              message.error(data.message);
            }
            // 重置分页按钮
            pagination.value.current = params.page;
            pagination.value.total = data.content.total;
          });
      };
  
      // 章节表单校验规则
      const rules = {
        name: [
          { required: true, message: "标题字段不能为空", trigger: "blur" },
          { whitespace: true, message: "标题字段不能为空", trigger: "blur" },
        ],
        sort: [
          {
            required: true,
            message: "序号字段不能为空",
            trigger: "blur",
            type: "any",
          },
        ],
      };
  
      // 章节表单
      const liveContentRef = ref();
      const liveContent = ref();
      const modalVisible = ref(false);
      const modalLoading = ref(false);
      const handleModalOk = () => {
        liveContentRef.value
          .validate()
          .then(() => {
            modalLoading.value = true;
            const saveObj = Tool.copy(liveContent.value);
            saveObj.liveId = route.query.courseId;
            saveObj.beginDate = moment(liveContent.value.beginDate).format(
              "YYYY-MM-DD"
            );
            saveObj.beginTime =
              saveObj.beginDate +
              " " +
              moment(liveContent.value.beginTime).format("HH:mm") +
              ":00";
            // 编辑保存章节
            axios
              .post("/api/admin/live/content/save", saveObj)
              .then((response) => {
                loading.value = false;
                const data = response.data;
                if (data.success) {
                  modalVisible.value = false;
                  modalLoading.value = false;
                  message.success("操作成功");
                  handleQuery({
                    page: pagination.value.current,
                    size: pagination.value.pageSize,
                  });
                } else {
                  modalLoading.value = false;
                  message.error(data.message);
                }
              });
          })
          .catch((error: ValidateErrorEntity) => {
            console.log("error", error);
          });
      };
  
      // 清除表单校验结果
      const clearValidate = () => {
        liveContentRef.value.clearValidate();
      };
  
      // 编辑方法
      const edit = (record: any) => {
        liveContent.value = Tool.copy(record);
        modalVisible.value = true;
      };
  
      // 新增直播课时方法
      const createLiveContent = () => {
        liveContent.value = {};
        modalVisible.value = true;
      };
  
      // 删除方法
      const handleDelete = (record: any) => {
        Modal.confirm({
          title: "该操作无法撤销-确认要删除吗？",
          icon: createVNode(ExclamationCircleOutlined),
          okText: "确定",
          cancelText: "取消",
          onOk() {
            axios
              .delete("/api/admin/live/content/delete/" + record.id)
              .then((response) => {
                const data = response.data;
                if (data.success) {
                  message.success("操作成功");
                  handleQuery({
                    page: pagination.value.current,
                    size: pagination.value.pageSize,
                  });
                }
              });
          },
        });
      };
  
      // 开启直播
      const startLive = (Record: any) => {
        axios
          .post("/api/admin/live/begin", {
            courseId: route.query.courseId,
            contentId: Record.id,
          })
          .then((res) => {
            const data = res.data;
            console.log(data);
            if (data.success) {
              router.push(
                "/admin/live?courseId=" +
                  route.query.courseId +
                  "&contentId=" +
                  Record.id +
                  "&content=" +
                  Record.name +
                  "&channel=" +
                  data.content.channel +
                  "&token=" +
                  data.content.token +
                  "&role=" +
                  data.content.role
              );
              console.log("跳转");
            }
          });
      };
  
      onMounted(() => {
        handleQuery({
          page: pagination.value.current,
          size: pagination.value.pageSize,
        });
      });
      return {
        liveContents,
        loading,
        columns,
        modalVisible,
        modalLoading,
        liveContent,
        pagination,
        rules,
        liveContentRef,
        handleQuery,
        clearValidate,
        edit,
        createLiveContent,
        handleModalOk,
        handleDelete,
        startLive,
      };
    },
  });
  </script>
  <style>
  </style>